#include <learn/check_gl.h>
#include <learn/geom/vec.h>

// 控制点数组
float ctrlPts[16][3] = {
    {-0.75, 0, -0.75}, {-0.5, 0.5, -0.75}, {0.5, 0.5, -0.75}, {0.75, 0, -0.75}, {-0.65, 0, -0.5}, {-0.4, 0.5, -0.5},
    {0.6, 0.5, -0.5},  {0.85, 0, -0.5},    {-0.75, 0, 0.5},   {-0.5, 0.5, 0.5}, {0.5, 0.5, 0.5},  {0.75, 0, 0.5},
    {-0.75, 0, 0.75},  {-0.5, 0.5, 0.75},  {0.5, 0.5, 0.75},  {0.75, 0, 0.75},
};

// 颜色数组
float colorPts[4][4] = {{1, 0, 0, 1}, {0, 1, 0, 1}, {0, 0, 1, 1}, {1, 1, 1, 1}};

void init()
{
    // 激活绘图子程序
    glMap1f(GL_MAP1_VERTEX_3, 0, 1, 3, 4, *ctrlPts);
    glEnable(GL_MAP1_VERTEX_3);

    // 激活绘图子程序
    // glMap2f(GL_MAP1_VERTEX_3, 0, 1, 3, 4, 0, 1, 3, 4, *ctrlPts);
    // glEnable(GL_MAP1_VERTEX_3);

    // 激活颜色插值
    glMap1f(GL_MAP1_COLOR_4, 0, 1, 4, 4, *colorPts);
    glEnable(GL_MAP1_COLOR_4);
}

void render()
{
    glPointSize(1);

    // 均匀绘制
    glMapGrid1f(50, 0, 1);       // (0,1) 划分成 50 份
    glEvalMesh1(GL_LINE, 0, 50); // 从 0 到 50 绘制连线

    glColor3f(1, 0, 0);
    glPointSize(5);

    // 绘制控制点
    glBegin(GL_POINTS);
    for (int k = 0; k < 16; k++)
    {
        glVertex3fv(&ctrlPts[k][0]);
    }
    glEnd();
}

int main()
{
    if (!glfwInit())
    {
        std::cerr << "Failed to initialize GLFW" << std::endl;
        return -1;
    }

    GLFWwindow *window = glfwCreateWindow(800, 600, "Three Stars", nullptr, nullptr);
    if (!window)
    {
        std::cerr << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

    init();
    while (!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT);
        render();
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();

    return 0;
}
